package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"shop/models"
)

type ShopController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	bian := c.GetString("bian")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	timed := c.GetString("timed")
	num, _ := c.GetInt("num")
	ling, _ := c.GetInt("ling")
	shi := c.GetString("shi")
	fan := c.GetString("fan")
	ftime := c.GetString("ftime")

	shop := models.Shop{
		Bian:  bian,
		Name:  name,
		Price: price,
		Timed: timed,
		Num:   num,
		Ling:  ling,
		Shi:   shi,
		Fan:   fan,
		Ftime: ftime,
	}

	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) List() {
	var shop []models.Shop
	err := models.DB.Find(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: shop,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Shop{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Update() {
	bian := c.GetString("bian")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	timed := c.GetString("timed")
	num, _ := c.GetInt("num")
	ling, _ := c.GetInt("ling")
	shi := c.GetString("shi")
	fan := c.GetString("fan")
	ftime := c.GetString("ftime")

	shop := models.Shop{
		Model: gorm.Model{},
		Bian:  bian,
		Name:  name,
		Price: price,
		Timed: timed,
		Num:   num,
		Ling:  ling,
		Shi:   shi,
		Fan:   fan,
		Ftime: ftime,
	}

	err := models.DB.Save(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
